package com.financing.platform.task;

import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import org.apache.bcel.generic.ARRAYLENGTH;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.financing.platform.dao.IHs300Dao;
import com.financing.platform.dto.CompositeIndexLogDTO;
import com.financing.platform.service.ICompositeIndexLogService;
import com.financing.platform.util.DateUtil;

@Component(value="fecthHS300Job")
public class FecthHS300Job {
	
	Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	private IHs300Dao ihs300Dao;
	
	public static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	
	public static List<String> dapan=new ArrayList<String>();
	
	@Autowired
	private ICompositeIndexLogService compositeIndexLogService;
	
	static{
		dapan.add("s_sh000001,上证指数");// 下午3点后收盘
//		dapan.put("s_sh000300","沪深300");// 下午3点后收盘
		dapan.add("s_sz399001,深证成指");// 下午3点后收盘
		dapan.add("s_sz399006,创业板指");// 下午3点后收盘
		dapan.add("int_hangseng,恒生指数");//下午4点
		dapan.add("int_sp500,标普500");//凌晨4点
		dapan.add("int_nasdaq,纳斯达克");//凌晨4点
		dapan.add("int_nikkei,日经225");//下午2点
		dapan.add("int_dax30,德国DAX");//下午11点半
//		dapan.put("int_dji","道琼斯");//凌晨4点
	}
	
	@Scheduled(cron = "0 0 05 * * ?") //发布  凌晨5点获取数据
//	@Scheduled(cron = "0 0/5 * * * ?") //测试 每5分钟更新一次数据
	public void fecthdapan(){
		log.info("come  in:"+DateUtil.getDate());
		for (int i=dapan.size()-1;i>=0;i--) {
			String key = dapan.get(i).split(",")[0];
			String value = dapan.get(i).split(",")[1];
			//先判断今日是否已经抓取
			try {
				CompositeIndexLogDTO compositeIndexLog=new CompositeIndexLogDTO();
				compositeIndexLog.setIndexCode(key);
				compositeIndexLog.setCurrentDate(DateUtil.getDate("yyyy-MM-dd"));
				List<CompositeIndexLogDTO> queryList = compositeIndexLogService.queryList(compositeIndexLog);
				if(queryList.size()==0){
					insertIndexLog(key,value);
				}else{
					log.info(key+",insertIndexLog 已存在记录");
				}
			} catch (SQLException e) {
				log.error("insertIndexLog error",e);
			}
			
		}
		log.info("end");
	}
	//检测 今日数据 是否完整
	@Scheduled(cron = "0 30 05 * * ?") 
	public void checke(){
		fecthdapan();
	}
	
	/***
	 * 存储     该方法存在问题（交易时间获取，数据需要另解析，存储错误）
	 * @param entry
	 */
	private void insertIndexLog(String key,String value) {
		String initUrl="http://hq.sinajs.cn/list="+key;
		URL url;
		try {
			url = new URL(initUrl);
			URLConnection openConnection = url.openConnection();
			HttpURLConnection httpConnection=(HttpURLConnection)openConnection;
			if (httpConnection.getResponseCode() >= 300) {
		        throw new Exception("HTTP Request is not success, Response code is " + httpConnection.getResponseCode());
		    }
			String result = IOUtils.toString(httpConnection.getInputStream(),"GBK");
			String[] split = result.split(",");
			String date=DateUtil.getDate("yyyy-MM-dd");
			String endPrice=split[1];
			String changePrice=split[2];
			String changePriceRate=split[3];
			changePriceRate=changePriceRate.replace("\";", "");
			CompositeIndexLogDTO indexLog=new CompositeIndexLogDTO();
			indexLog.setCurrentDate(date);
			BigDecimal indexEndPrice = new BigDecimal(endPrice);
			indexLog.setIndexEndPrice(indexEndPrice);
			indexLog.setIndexName(value);
			if(key.matches("^int.*")&&!key.equals("int_hangseng")){
				indexLog.setIndexType("2");
			}else{
				indexLog.setIndexType("1");
			}
			BigDecimal indexChangePrice = new BigDecimal(changePrice);
			indexLog.setIndexChangePrice(indexChangePrice);
			indexLog.setIndexCode(key);
			indexLog.setIndexChangePriceRate(changePriceRate);
			indexLog.setCreateBy("system");
			indexLog.setCreateDate(new Date());
//			if(key.equals("s_sz399006")||key.equals("int_nikkei")){
//				indexLog.setDeleteTag("2");//不展示
//			}else{
//				indexLog.setDeleteTag("1");
//			}
			indexLog.setDeleteTag("1");
			System.out.println(indexLog);
			compositeIndexLogService.insert(indexLog);
		} catch (Exception e) {
			log.error("FecthHS300Job.dapan error",e);
		}
	}
	
	
	
	
}
